<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission(1, '0')">添加权限</el-button>
        </div>

        <el-table row-key="id" :data="permissionList" border>
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button v-if="scope.row.type === 1" type="text" @click="addPermission(2, scope.row.id)">添加</el-button>
              <el-button type="text" @click="updatePermission(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="deletePermission(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog :title="isEdit ? '编辑权限点' : '新增权限点'" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="editPermission">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>

      </el-card>
    </div>
  </div>
</template>

<script>
// 获取权限列表  新增权限  获取权限详情  更新权限   删除权限
import { getPermissionList, addPermission, getPermissionDetail, updatePermission, delPermission } from '@/api/permission'
// 导入扁平数组转换树形结构
import { treeFn } from '@/utils'
export default {
  name: 'Permission',
  data() {
    // 校验在新增时不能在同级中出现重复的名称,并且在编辑时排除自身
    var checkName = (rule, value, callback) => {
      // 先用数组的过滤方法找到所有的同级
      let sameLevelList = this.originList.filter(item => item.pid === this.formData.pid)

      // 如果是编辑状态下,需要排除自己  排除自己需要先找到所有的同级,找到同级之后
      if (this.isEdit) {
        sameLevelList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }

      // 用数组的map方法,拿到所有同级的name值,在将同级的name值和要添加的name进行判断
      sameLevelList.map(item => item.name.trim()).includes(value) ? callback(new Error(`该${value}名称已经存在`)) : callback()
    }
    var validateCode = (rule, value, callback) => {
      // 先获取到格式化数组中所有的标识
      let logoList = this.originList
      // 如果是编辑时,需要将自己排除
      if (this.isEdit) {
        logoList = this.originList.filter(item => item.id !== this.formData.id)
      }

      logoList.map(item => item.code).includes(value) ? callback(new Error(`该${value}标识已经存在`)) : callback()
    }

    return {
      permissionList: [], // 权限管理列表数据
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validateCode, trigger: 'blur' }
        ]
      },
      isEdit: false, // 控制编辑还是新增的显示与隐藏
      originList: [] // 格式化后的数据
    }
  },
  created() {
    // 调用获取权限列表数据
    this.getPermissionList()
  },
  methods: {
    // 点击删除按钮
    async deletePermission(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmRes === 'cancel') return this.$message('您取消删除成功')

      const res = await delPermission(id)
      this.$message.success(res.message)
      // 重新获取列表数据
      this.getPermissionList()
    },

    // 点击确认按钮
    editPermission() {
      // 先进行兜底校验
      this.$refs.perForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.editPermissionFn() : this.addPermissionFn()
      })
    },

    // 编辑权限
    async editPermissionFn() {
      const res = await updatePermission(this.formData)
      this.$message.success(res.message)
      this.showDialog = false
      this.getPermissionList()
    },

    // 新增权限
    async addPermissionFn() {
      const res = await addPermission(this.formData)
      this.$message.success(res.message)
      // 重新获取列表数据
      this.getPermissionList()
      this.showDialog = false
    },

    // 点击编辑按钮
    async updatePermission(id) {
      this.isEdit = true
      const res = await getPermissionDetail(id)
      // 进行数据回显
      this.formData = res.data
      this.showDialog = true
    },

    // 点击添加权限
    addPermission(type, pid) {
      this.isEdit = false
      this.formData.type = type
      this.formData.pid = pid
      this.showDialog = true
    },
    // 按钮关闭事件
    btnCancel() {
      console.log(1)
      // 清空表单输入框
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }

      // 清除表单校验
      this.$refs.perForm.resetFields()
      this.showDialog = false
    },
    // 获取权限列表数据
    async getPermissionList() {
      const res = await getPermissionList()
      // 格式化数据
      this.originList = res.data.map(item => ({
        id: item.id,
        pid: item.pid,
        code: item.code,
        name: item.name
      }))
      this.permissionList = treeFn(res.data, '0')
    }
  }
}
</script>

<style lang="scss" scoped></style>

